import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:thinking/config/Color.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/widget/WaterFallFlow/WaterFallFlow.dart';
import 'package:thinking/widget/_.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';


class ClassList extends StatefulWidget{

  final String classValue;
  final Function? historySplashCallBack;
  ClassList({required this.classValue, this.historySplashCallBack});

  @override
  _ClassList createState() => _ClassList(classValue: classValue,historySplashCallBack: historySplashCallBack);

}

class _ClassList extends State<ClassList> with AutomaticKeepAliveClientMixin{

  @override
  bool get wantKeepAlive => true;

  String classValue;
  Function? historySplashCallBack;
  _ClassList({required this.classValue,this.historySplashCallBack});
  late Map<String,dynamic> classScreen;
  late List<Map<String,dynamic>> classScreenItems;
  late EasyRefreshController _easyRefreshController;
  CountryPage countryPage = CountryPage();
  List<Think> thinkList = [];
  Map<String,dynamic> screenIndexMap = {};
  bool isLoading = false;
  List<BannerItem> bannerData  = [];

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    if(classValue !='分历史'){
      classScreen =  Config.classListScreen[Config.classListScreen.indexWhere((item) => item['name'] == classValue)];
      classScreenItems = classScreen['classList'];
      classScreenItems.forEach((Map<String,dynamic> e) =>{
        screenIndexMap["${e["entityName"].substring(0,e["entityName"].length-6)}"] = 0
      });
    }
    getClassValue();
  }


  @override
  void dispose() {
    _easyRefreshController.dispose();
    super.dispose();
  }


  getClassValue() async{

    switch(classValue){
      case '分历史':
        return getHistoryValue();
      default:
        return getClassListValue();
    }

  }

  Future<void> getHistoryValue() async{

    var res = await HistoryService.getHistoryThink(params: {
      "think_Page":countryPage.thinkPage,
      "think_Count":countryPage.thinkCount,
      "history_Index":SPreferences().getInt('history_Index')
    });
    if(countryPage.canThink)thinkList  = [...thinkList,...?res.thinkData];
    BotToast.showText(text: res.thinkData!.length == 0 || !countryPage.canThink?'没有更多think了哦~':'更新了${res.thinkData!.length}条think~');
    if(res.thinkData!.length<countryPage.thinkCount) {
      countryPage.setCanThink =false;
    }
    this.isLoading = true;
    setState(() {

    });
  }

  Future<void> getClassListValue({bool isScreen:false}) async{
    if(isScreen){
      this.isLoading = false;
      countryPage.setThinkPage =0;
      countryPage.setCanThink = true;
      thinkList =[];
      setState(() {

      });
    }
    var someParams = {
      "classList_name":classValue,
      "think_Page":countryPage.thinkPage,
      "think_Count":countryPage.thinkCount,

    };
    var res = await ClassListService.getClassListValue(params: {
      ...someParams,
      ...screenIndexMap

    });
    bannerData = res.bannerData!;
    if(countryPage.canThink)thinkList  = [...thinkList,...?res.thinkData];
    BotToast.showText(text: res.thinkData!.length == 0 || !countryPage.canThink?'没有更多think了哦~':'更新了${res.thinkData!.length}条think~');
    if(res.thinkData!.length<countryPage.thinkCount) {
      countryPage.setCanThink =false;
    }
    this.isLoading = true;
    setState(() {

    });
  }

  Widget easyRefresh(Widget child) {
    return EasyRefresh(
      child: child,
      header: BezierCircleHeader(backgroundColor: ColorConfig.ThemeColor),
      footer: BezierBounceFooter(backgroundColor: ColorConfig.ThemeColor),
      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      controller: _easyRefreshController,
      bottomBouncing: true,
      onRefresh: () async {
        if(!this.isLoading) return;
        countryPage.setThinkPage =0;
        countryPage.setCanThink = true;
        thinkList = [];
        await getClassValue();
        _easyRefreshController.finishRefresh(success: true);
      },
      onLoad: () async {
        if(!this.isLoading) return;
        if(countryPage.canThink){
          countryPage.setThinkPage = countryPage.thinkPage + 1;
        }
        await getClassValue();
        _easyRefreshController.finishLoad(success: true);
      },
    );
  }

  Future<dynamic> showModalBottom(List<ClassScreen> e,int i){

      return showModalBottomSheet(
          context: context,
          elevation: 10,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
          builder: (BuildContext context) {
            return Container(
              height:Screen.setHeight(300),
              padding: EdgeInsets.only(top: Screen.setHeight(10)),
              child: ListView(
                shrinkWrap: true,
                children:  e.map((e) =>  Column(
                  children: [
                    Container(
                      height: 50,
                      child: TextButton(
                        style: ButtonStyle(
                          overlayColor: MaterialStateProperty.all(
                              ColorConfig.LineColor
                          ),
                        ),
                        child: Center(
                          child: Text(
                            e.name!,
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                                color: Colors.black
                            ),
                          ),
                        ),
                        onPressed: (){
                          classScreenItems[i]['name'] =  e.name == '全选'?Config.classListScreenCopy[Config.classListScreenCopy.indexWhere((item) => item['name'] == classValue)]['classList'][i]['name']:e.name;
                          setState(() {
                          });
                          screenIndexMap["${classScreenItems[i]['entityName'].substring(0,classScreenItems[i]['entityName'].length-6)}"] = e.id;
                          Modular.to.pop();
                          getClassListValue(isScreen: true);
                        },
                      ),
                    ),
                    Line(height: 1,width: Screen.setWidth(Screen.width(context)-40),),
                  ],
                )).toList()

              ),
            );
          });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return easyRefresh(ListView(
      shrinkWrap: true,
      physics: BouncingScrollPhysics(),
      children: [
        SizedBox(height: Screen.setHeight(10),),
        bannerData.length != 0?BannerWidget(bannerData: bannerData):Container(),
        Panel(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [


              classValue == '分历史'?ElevatedButton(
                style: ButtonStyle(
                  padding: MaterialStateProperty.all(EdgeInsets.all(8)),
                  minimumSize: MaterialStateProperty.all(Size(40, 30)),
                  textStyle: MaterialStateProperty.all(
                      TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
                  backgroundColor:
                  MaterialStateProperty.all(ColorConfig.WhiteBackColor),
                  side:
                  MaterialStateProperty.all(BorderSide(color: ColorConfig.ThemeColor, width: 1)),
                  shape: MaterialStateProperty.all(RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(5)))),
                  elevation: MaterialStateProperty.all(2),
                  foregroundColor: MaterialStateProperty.all(ColorConfig.ThemeColor),
                ),
                onPressed: () {
                  historySplashCallBack!();
                },
                child: Text(SPreferences().getString('history_Title')),
              ):
                Expanded(child: Container(
                  height: Screen.setHeight(50),
                  child: ListView(
                    shrinkWrap: true,
                    padding: EdgeInsets.all(0),
                    physics: BouncingScrollPhysics(),
                    scrollDirection: Axis.horizontal,
                    children: [Row(
                      children: classScreenItems.asMap()
                          .keys
                          .map((e) =>
                          Container(
                            margin: EdgeInsets.only(right: Screen.setWidth(5)),
                            child: ElevatedButton(
                              style: ButtonStyle(
                                padding: MaterialStateProperty.all(EdgeInsets.all(8)),
                                minimumSize: MaterialStateProperty.all(Size(40, 30)),
                                textStyle: MaterialStateProperty.all(
                                    TextStyle(fontSize: 13, fontWeight: FontWeight.w600)),
                                backgroundColor:
                                MaterialStateProperty.all(ColorConfig.WhiteBackColor),
                                side:
                                MaterialStateProperty.all(BorderSide(color: ColorConfig.ThemeColor, width: 1)),
                                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                                    borderRadius: BorderRadius.all(Radius.circular(5)))),
                                elevation: MaterialStateProperty.all(2),
                                foregroundColor: MaterialStateProperty.all(ColorConfig.ThemeColor),
                              ),
                              onPressed: () async{
                                var res = await ClassListService.getClassScreen(params: {
                                  "entity_name":classScreenItems[e]['entityName']
                                });
                                res!.insert(0,ClassScreen.fromJson({"name":'全选',"id":0}));
                                await showModalBottom(res,e);
                              },

                              child: Text('${classScreenItems[e]['name']}'),
                            ),
                          )
                      ).toList(),
                    )
                    ],
                  ),
                )),

            ],
          ),
        ),
        this.isLoading?Empty(
          isShow: this.thinkList.length == 0,
          child: SpannableCountCountPage(thinkDataList: thinkList),
        ):Loading(),
      ],
    ));

  }

}